<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElSwitch, ElButton, ElIcon, ElTabs, ElTabPane, ElCheckbox, ElCheckboxGroup, ElColorPicker, ElSlider, ElUpload, ElMessage, ElNotification, ElDialog, ElTable, ElTableColumn, ElPagination } from 'element-plus'
import { Save, Refresh, User, Lock, Bell, Cog, Role, ChevronDown, Search, Plus, Trash, CheckCircle, AlertTriangle } from '@element-plus/icons-vue'

// 当前激活的标签页
const activeTab = ref('system')
// 加载状态
const loading = ref(false)
// 保存状态
const saving = ref(false)
// 角色管理对话框
const roleDialogVisible = ref(false)
// 新建/编辑角色
const isEditRole = ref(false)
// 当前编辑的角色
const currentRole = ref({})
// 角色列表
const roleList = ref([])
// 权限选项
const permissionOptions = ref([
  { id: 'dashboard', label: '仪表盘访问' },
  { id: 'students', label: '学生管理' },
  { id: 'courses', label: '课程管理' },
  { id: 'statistics', label: '统计分析' },
  { id: 'messages', label: '消息管理' },
  { id: 'files', label: '文件管理' },
  { id: 'settings', label: '系统设置' },
  { id: 'roles', label: '角色管理' },
])

// 系统设置表单数据
const systemForm = reactive({
  siteName: '智慧教育平台',
  siteDescription: '专注于提供优质的教育资源和管理服务',
  logoUrl: '',
  faviconUrl: '',
  copyright: '© 2023 智慧教育平台 版权所有',
  isMaintenanceMode: false,
  maintenanceMessage: '系统维护中，请稍后访问',
  maxFileSize: 10,
  defaultLanguage: 'zh-CN',
  timezone: 'Asia/Shanghai'
})

// 用户设置表单数据
const userForm = reactive({
  username: 'admin',
  email: 'admin@example.com',
  fullName: '管理员',
  avatar: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: '',
  isTwoFactorAuth: false,
  notificationEmail: true,
  notificationSms: false,
  language: 'zh-CN',
  theme: 'light'
})

// 通知设置表单数据
const notificationForm = reactive({
  emailNotifications: {
    newMessage: true,
    courseUpdate: true,
    assignmentDue: true,
    systemAnnouncement: true
  },
  smsNotifications: {
    newMessage: false,
    courseUpdate: false,
    assignmentDue: true,
    systemAnnouncement: true
  },
  pushNotifications: {
    newMessage: true,
    courseUpdate: true,
    assignmentDue: true,
    systemAnnouncement: true
  },
  notificationSound: true,
  notificationVibration: true
})

// 角色表单数据
const roleForm = reactive({
  name: '',
  description: '',
  permissions: []
})

// 加载角色列表
const loadRoles = async () => {
  loading.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    // 模拟数据
    roleList.value = [
      { id: 1, name: '超级管理员', description: '拥有系统所有权限', permissions: ['dashboard', 'students', 'courses', 'statistics', 'messages', 'files', 'settings', 'roles'] },
      { id: 2, name: '教师', description: '管理课程和学生', permissions: ['dashboard', 'students', 'courses', 'statistics', 'messages', 'files'] },
      { id: 3, name: '学生', description: '学习课程和提交作业', permissions: ['dashboard', 'messages', 'files'] },
      { id: 4, name: '访客', description: '只读访问权限', permissions: ['dashboard'] }
    ]
  } catch (error) {
    ElNotification.error('获取角色列表失败')
    console.error('Failed to load roles:', error)
  } finally {
    loading.value = false
  }
}

// 保存系统设置
const saveSystemSettings = async () => {
  saving.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElNotification.success('系统设置保存成功')
  } catch (error) {
    ElNotification.error('系统设置保存失败')
    console.error('Failed to save system settings:', error)
  } finally {
    saving.value = false
  }
}

// 保存用户设置
const saveUserSettings = async () => {
  saving.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElNotification.success('用户设置保存成功')
  } catch (error) {
    ElNotification.error('用户设置保存失败')
    console.error('Failed to save user settings:', error)
  } finally {
    saving.value = false
  }
}

// 保存通知设置
const saveNotificationSettings = async () => {
  saving.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    ElNotification.success('通知设置保存成功')
  } catch (error) {
    ElNotification.error('通知设置保存失败')
    console.error('Failed to save notification settings:', error)
  } finally {
    saving.value = false
  }
}

// 打开添加角色对话框
const openAddRoleDialog = () => {
  isEditRole.value = false
  roleForm.name = ''
  roleForm.description = ''
  roleForm.permissions = []
  roleDialogVisible.value = true
}

// 打开编辑角色对话框
const openEditRoleDialog = (role) => {
  isEditRole.value = true
  currentRole.value = { ...role }
  roleForm.name = role.name
  roleForm.description = role.description
  roleForm.permissions = [...role.permissions]
  roleDialogVisible.value = true
}

// 关闭角色对话框
const closeRoleDialog = () => {
  roleDialogVisible.value = false
}

// 保存角色
const saveRole = async () => {
  if (!roleForm.name) {
    ElMessage.error('角色名称不能为空')
    return
  }

  saving.value = true
  try {
    // 模拟API请求延迟
    await new Promise(resolve => setTimeout(resolve, 1000))

    if (isEditRole.value) {
      // 更新角色
      const index = roleList.value.findIndex(item => item.id === currentRole.value.id)
      if (index !== -1) {
        roleList.value[index] = {
          ...roleList.value[index],
          name: roleForm.name,
          description: roleForm.description,
          permissions: [...roleForm.permissions]
        }
      }
      ElNotification.success('角色更新成功')
    } else {
      // 添加新角色
      const newRole = {
        id: Date.now(),
        name: roleForm.name,
        description: roleForm.description,
        permissions: [...roleForm.permissions]
      }
      roleList.value.push(newRole)
      ElNotification.success('角色添加成功')
    }

    roleDialogVisible.value = false
  } catch (error) {
    ElNotification.error('保存角色失败')
    console.error('Failed to save role:', error)
  } finally {
    saving.value = false
  }
}

// 删除角色
const deleteRole = async (id) => {
  // 不能删除超级管理员角色
  if (id === 1) {
    ElMessage.error('不能删除超级管理员角色')
    return
  }

  try {
    const result = await ElMessageBox.confirm('确定要删除该角色吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    if (result === 'confirm') {
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 500))
      // 删除角色
      roleList.value = roleList.value.filter(item => item.id !== id)
      ElNotification.success('角色删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElNotification.error('角色删除失败')
      console.error('Failed to delete role:', error)
    }
  }
}

// 上传图片
const handleAvatarUpload = (response, file, fileList) => {
  // 模拟上传成功
  ElMessage.success('头像上传成功')
  userForm.avatar = URL.createObjectURL(file.raw)
}

// 上传Logo
const handleLogoUpload = (response, file, fileList) => {
  // 模拟上传成功
  ElMessage.success('Logo上传成功')
  systemForm.logoUrl = URL.createObjectURL(file.raw)
}

// 刷新数据
const refreshData = () => {
  loadRoles()
}

// 页面加载时获取数据
onMounted(() => {
  loadRoles()
})
</script>

<template>
  <div class="settings-container">
    <div class="header">
      <h2>系统设置</h2>
      <div class="action-buttons">
        <el-button @click="refreshData">
          <el-icon><Refresh /></el-icon> 刷新
        </el-button>
      </div>
    </div>

    <el-tabs v-model="activeTab" type="border-card" style="margin-top: 20px;">
      <el-tab-pane label="系统设置" name="system" :icon="<Cog />">
        <el-form :model="systemForm" label-width="180px" class="settings-form">
          <el-form-item label="网站名称">
            <el-input v-model="systemForm.siteName" placeholder="请输入网站名称" />
          </el-form-item>
          <el-form-item label="网站描述">
            <el-input v-model="systemForm.siteDescription" type="textarea" placeholder="请输入网站描述" />
          </el-form-item>
          <el-form-item label="网站Logo">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleLogoUpload"
              :before-upload="beforeUpload"
              action=""
            >
              <img v-if="systemForm.logoUrl" :src="systemForm.logoUrl" class="avatar">
              <div v-else class="avatar-uploader-icon">
                <Plus size="28" />
              </div>
            </el-upload>
            <div class="el-upload__tip">支持JPG、PNG格式，大小不超过2MB</div>
          </el-form-item>
          <el-form-item label="网站版权信息">
            <el-input v-model="systemForm.copyright" placeholder="请输入版权信息" />
          </el-form-item>
          <el-form-item label="维护模式">
            <el-switch v-model="systemForm.isMaintenanceMode" />
          </el-form-item>
          <el-form-item label="维护消息" v-if="systemForm.isMaintenanceMode">
            <el-input v-model="systemForm.maintenanceMessage" type="textarea" placeholder="请输入维护消息" />
          </el-form-item>
          <el-form-item label="最大文件上传大小(MB)">:
            <el-slider v-model="systemForm.maxFileSize" :min="1" :max="100" :step="1" show-input />
          </el-form-item>
          <el-form-item label="默认语言">
            <el-select v-model="systemForm.defaultLanguage" placeholder="请选择语言">
              <el-option label="简体中文" value="zh-CN" />
              <el-option label="English" value="en-US" />
            </el-select>
          </el-form-item>
          <el-form-item label="时区">
            <el-select v-model="systemForm.timezone" placeholder="请选择时区">
              <el-option label="Asia/Shanghai (GMT+8)" value="Asia/Shanghai" />
              <el-option label="UTC" value="UTC" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveSystemSettings" :loading="saving">
              <el-icon><Save /></el-icon> 保存设置
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="用户设置" name="user" :icon="<User />">
        <el-form :model="userForm" label-width="180px" class="settings-form">
          <el-form-item label="用户名">
            <el-input v-model="userForm.username" placeholder="请输入用户名" disabled />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="userForm.email" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="姓名">
            <el-input v-model="userForm.fullName" placeholder="请输入姓名" />
          </el-form-item>
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              :show-file-list="false"
              :on-success="handleAvatarUpload"
              :before-upload="beforeUpload"
              action=""
            >
              <img v-if="userForm.avatar" :src="userForm.avatar" class="avatar">
              <div v-else class="avatar-uploader-icon">
                <Plus size="28" />
              </div>
            </el-upload>
          </el-form-item>
          <el-form-item label="旧密码">
            <el-input v-model="userForm.oldPassword" type="password" placeholder="请输入旧密码" />
          </el-form-item>
          <el-form-item label="新密码">
            <el-input v-model="userForm.newPassword" type="password" placeholder="请输入新密码" />
          </el-form-item>
          <el-form-item label="确认新密码">
            <el-input v-model="userForm.confirmPassword" type="password" placeholder="请确认新密码" />
          </el-form-item>
          <el-form-item label="双因素认证">
            <el-switch v-model="userForm.isTwoFactorAuth" />
          </el-form-item>
          <el-form-item label="语言偏好">
            <el-select v-model="userForm.language" placeholder="请选择语言">
              <el-option label="简体中文" value="zh-CN" />
              <el-option label="English" value="en-US" />
            </el-select>
          </el-form-item>
          <el-form-item label="主题">
            <el-select v-model="userForm.theme" placeholder="请选择主题">
              <el-option label="浅色" value="light" />
              <el-option label="深色" value="dark" />
              <el-option label="跟随系统" value="system" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveUserSettings" :loading="saving">
              <el-icon><Save /></el-icon> 保存设置
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="通知设置" name="notification" :icon="<Bell />">
        <el-form :model="notificationForm" label-width="180px" class="settings-form">
          <el-form-item label="邮件通知">
            <el-checkbox-group v-model="notificationForm.emailNotifications">
              <el-checkbox label="新消息" name="newMessage" />
              <el-checkbox label="课程更新" name="courseUpdate" />
              <el-checkbox label="作业截止提醒" name="assignmentDue" />
              <el-checkbox label="系统公告" name="systemAnnouncement" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="短信通知">
            <el-checkbox-group v-model="notificationForm.smsNotifications">
              <el-checkbox label="新消息" name="newMessage" />
              <el-checkbox label="课程更新" name="courseUpdate" />
              <el-checkbox label="作业截止提醒" name="assignmentDue" />
              <el-checkbox label="系统公告" name="systemAnnouncement" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="推送通知">
            <el-checkbox-group v-model="notificationForm.pushNotifications">
              <el-checkbox label="新消息" name="newMessage" />
              <el-checkbox label="课程更新" name="courseUpdate" />
              <el-checkbox label="作业截止提醒" name="assignmentDue" />
              <el-checkbox label="系统公告" name="systemAnnouncement" />
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="通知声音">
            <el-switch v-model="notificationForm.notificationSound" />
          </el-form-item>
          <el-form-item label="通知震动">
            <el-switch v-model="notificationForm.notificationVibration" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="saveNotificationSettings" :loading="saving">
              <el-icon><Save /></el-icon> 保存设置
            </el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <el-tab-pane label="角色管理" name="roles" :icon="<Role />">
        <div class="role-management-header">
          <el-button type="primary" @click="openAddRoleDialog">
            <el-icon><Plus /></el-icon> 新增角色
          </el-button>
        </div>

        <el-table
          v-loading="loading"
          :data="roleList"
          style="width: 100%; margin-top: 20px;"
          border
        >
          <el-table-column prop="id" label="ID" width="80" align="center" />
          <el-table-column prop="name" label="角色名称" width="180" />
          <el-table-column prop="description" label="角色描述" width="300" />
          <el-table-column label="权限" width="300">
            <template #default="{ row }">
              <div class="permissions">
                <el-tag v-for="perm in row.permissions" :key="perm" size="small" style="margin-right: 5px; margin-bottom: 5px;">
                  {{ getPermissionLabel(perm) }}
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click="openEditRoleDialog(row)">
                <el-icon><Edit /></el-icon> 编辑
              </el-button>
              <el-button type="danger" size="small" @click="deleteRole(row.id)" :disabled="row.id === 1">
                <el-icon><Trash /></el-icon> 删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 角色对话框 -->
    <el-dialog
      v-model="roleDialogVisible"
      :title="isEditRole ? '编辑角色' : '添加角色'"
      width="600px"
    >
      <el-form :model="roleForm" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" type="textarea" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="角色权限">
          <el-checkbox-group v-model="roleForm.permissions">
            <el-checkbox
              v-for="perm in permissionOptions"
              :key="perm.id"
              :label="perm.id"
            >
              {{ perm.label }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="closeRoleDialog">取消</el-button>
        <el-button type="primary" @click="saveRole" :loading="saving">
          <el-icon><Save /></el-icon> {{ isEditRole ? '更新' : '保存' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.settings-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.settings-form {
  padding: 20px;
  background-color: #fafafa;
  border-radius: 5px;
}

.avatar-uploader {
  display: flex;
  align-items: center;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

.avatar-uploader-icon {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 50%;
  color: #8c8c8c;
  background-color: #f5f5f5;
}

.role-management-header {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.permissions {
  display: flex;
  flex-wrap: wrap;
}
</style>